package com.mlk.rbac.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mlk.core.config.UserConfig;
import com.mlk.core.constants.Constant;
import com.mlk.core.util.JSONUtils;
import com.mlk.rbac.mapper.SysUserMapper;
import com.mlk.rbac.po.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户信息的监听器
 */
@Component
@Slf4j
public class UserListener implements ApplicationListener<ContextRefreshedEvent>{

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        log.debug("user listener start");
        List<SysUser> users = this.sysUserMapper.selectList(new EntityWrapper<>(SysUser.builder().status(Constant.status_ok).build()));
        users.stream().forEach((user)->{
            redisTemplate.opsForValue().set(UserConfig.CACHE_PREFIX+user.getId(), JSONUtils.toJSONString(user));
        });
    }
}
